package cn.yanglq.Rss.web.controller.register;

import cn.yanglq.Rss.web.WebConsts;
import cn.yanglq.Rss.web.common.vo.ApiResult;
import cn.yanglq.Rss.web.controller.BaseController;
import cn.yanglq.Rss.web.model.User;
import cn.yanglq.Rss.web.service.RegisterService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by yanglq on 2017/6/13.
 */

@Controller
@RequestMapping("/register")
public class RegisterControler extends BaseController {
    @Autowired
    private RegisterService registerService;

    @RequestMapping
    public String registerPage(HttpSession httpSession) {

        if (httpSession.getAttribute(WebConsts.SESSION_USERID) != null) {
            return "redirect:/main";
        }
        return "/register/register";
    }

    @RequestMapping("/register")
    @ResponseBody
    public ApiResult register(@RequestParam(value = "name", required = true) String name,
                              @RequestParam(value = "phoneno", required = true) String phoneno,
                              @RequestParam(value = "password", required = true) String password,
                              @RequestParam(value = "email", required = true) String email,
                              @RequestParam(value = "username", required = true) String username,
                              HttpServletRequest request, HttpSession httpSession) {
        ApiResult result = new ApiResult();
        User user = registerService.searchUser(name);
        if (user != null) {
            result.setSuccess(false);
            result.setErrorcode(1);
            result.setMessage("用户已存在！");
        }
        registerService.userRegister(name, DigestUtils.md5Hex(password), email, username, phoneno);
        result.setSuccess(true);
        result.setErrorcode(0);
        result.setMessage("注册成功！");
        result.setDatas(httpSession.getServletContext().getContextPath()
                + "/login");

        return result; //校验通过返回成功
    }

}
